<?php
/**
 * +----------------------------------------------------------------------
 * | [ DO WHAT YOU LOVE AND FUCK THE REST ]
 * +----------------------------------------------------------------------
 * | EMAIL: < 931274989@qq.com >
 * +----------------------------------------------------------------------
 * | WECHAT: xzc016
 * +----------------------------------------------------------------------
 * | 邮箱设置
 * +----------------------------------------------------------------------
 */
namespace app\admin\controller;

use app\admin\validate\Email as EmailValidate;

use PHPMailer\PHPMailer\PHPMailer;
use think\facade\View;
use think\facade\Db;

class Email extends Base
{
  // 路由列表
  public function index()
  {
    $data = Db::name('email')->where('email','email')->find();
    View::assign('data',$data);
    return View::fetch();
  }

  // 修改邮件配置
  public function emailPost() 
  {
    if($this->request->isPost()) {
      $post = $this->request->post();
      //验证  
      (new EmailValidate())->goCheck();
      if(false == Db::name('email')->where('email','email')->update($post)) {
        return error('提交失败');
      } else {
        adminLog();//写入日志
        return success('提交成功','admin/Email/index');
      }
    } else {
      return error('非法请求');
    }
  }

  // 发送测试邮件
  public function trySend()
  {
    if($this->request->isPost()) {
      $post = $this->request->post();
      //验证  
      // (new EmailValidate())->goCheck();
      $address = $post['email'];
      $mailto = self::SendMail($address);
      if(false == $mailto) {
        return error($mailto);
      } else {
        return error($mailto);
        adminLog($address);//写入日志
        return success('邮件发送成功');
      }
      // dump($mailto);
    } else {
      return View::fetch();
    }
  }

  /**
   * [SendMail 邮件发送]
   * @param [type] $address  [description]
   */
  private static function SendMail($address)
  {
    $mail = new PHPMailer();      
    $mail->SMTPDebug = 1;
    // 设置PHPMailer使用SMTP服务器发送Email
    $mail->IsSMTP();
    $mail->SMTPAuth = true;
    // 设置邮件的字符编码，若不指定，则为'UTF-8'
    $mail->CharSet='UTF-8'; 
    // smtp需要鉴权 这个必须是true
    $mail->SMTPAuth=true;
    //设置html发送格式
    $mail->isHTML(true); 
    // 设置使用ssl加密方式登录鉴权
    $mail->SMTPSecure = 'ssl';
    // 设置ssl连接smtp服务器的远程服务器端口号
    $mail->Port = 465;
    
    // 设置收件人邮箱地址 添加多个收件人 则多次调用方法即可
    $mail->AddAddress($address); 
    $data = Db::name('email')->where('email','email')->find();
    // 设置邮件标题
    $mail->Subject=$data['title'];
    // 设置邮件正文
    $mail->Body=$data['content']; 
    // 设置邮件头的From字段。设置发件人邮箱地址 同登录账号
    $mail->From=$data['from_email']; 
    // 设置发件人名字
    $mail->FromName=$data['from_name'];  
    // 设置SMTP服务器。
    $mail->Host=$data['smtp'];
    // 设置用户名和密码。
    $mail->Username=$data['username'];
    $mail->Password=$data['password']; 
    // 为该邮件添加附件
    // $mail->addAttachment('./example.pdf');
    // 发送邮件。返回状态
    return($mail->Send());
  }

}

?>